//
//  JKLockView.m
//  newTestGit
//
//  Created by fangjs on 16/2/18.
//  Copyright © 2016年 Hongshi. All rights reserved.
//

#import "JKLockView.h"

//const:定义只读的变量名,在其他的类中不能声明同样的变量名
CGFloat const btnCount = 9;
CGFloat const btnW = 74;
CGFloat const btnH = 74;
CGFloat const viewY = 300;
int const columnCount = 3;

#define kScreenWidth  [UIScreen mainScreen].bounds.size.width
#define kScreenHeight  [[UIScreen mainScreen].bounds.size.height]

typedef NS_ENUM(NSInteger,MODE_STATE) {
    MODE_STATE_DEFAULT,
    MODE_STATE_FORGOT,
    MODE_STATE_CHANGE,
    MODE_STATE_CANCLE,
    MODE_STATE_COUNT
};


@interface JKLockView () 

//匿名扩展(类目的特例),可以声明属性
@property (nonatomic , strong) NSMutableArray *selecteBtns;
@property (nonatomic, assign) CGPoint currentPoint;
@property (nonatomic, strong) UILabel *contentLabel;
@property (nonatomic, assign) MODE_STATE state;
@property (nonatomic , strong) DiskGesturePassword *diskPassword;
@property (nonatomic , assign) NSInteger mode;
@property (nonatomic, strong) UIButton *changebtn;
@property (nonatomic, strong) UIButton *forgotbtn;

@end

@implementation JKLockView

//创建数组
- (NSMutableArray *) selecteBtns {
    if (_selecteBtns == nil) {
        _selecteBtns = [NSMutableArray array];
    }
    return _selecteBtns;
}


//通过代码创建会调用这个方法
- (instancetype) initWithFrame:(CGRect)frame {
    if (self == [super initWithFrame:frame]) {
        [self AddButton];
        self.mode = MODE_STATE_DEFAULT;
        self.diskPassword = [DiskGesturePassword shareDiskGestruePassword];
        self.contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth/2 - kScreenWidth/6, 10, kScreenWidth/3, 44)];
        self.contentLabel.textAlignment = NSTextAlignmentCenter;
        self.contentLabel.textColor = [UIColor whiteColor];
        self.contentLabel.text = @"输入密码";
        [self addSubview:self.contentLabel];
    }
    return self;
}

//通过 storyboard或者 xib 创建的时候会调用
- (id) initWithCoder:(NSCoder *)aDecoder {
    if (self == [super initWithCoder:aDecoder]) {
        [self AddButton];
        self.mode = MODE_STATE_DEFAULT;
        self.diskPassword = [DiskGesturePassword shareDiskGestruePassword];
        self.contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth/2 - kScreenWidth/6, 10, kScreenWidth/3, 44)];
        self.contentLabel.textAlignment = NSTextAlignmentCenter;
        self.contentLabel.textColor = [UIColor whiteColor];
        self.contentLabel.text = @"输入密码";
        [self addSubview:self.contentLabel];
    }
    return self;
}
- (void) AddButton {
    CGFloat height = 0;
    for (int i = 0; i < btnCount; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        //设置默认的图片
        [btn setBackgroundImage:[UIImage imageNamed:@"gesture_node_normal"] forState:UIControlStateNormal];
        
        btn.userInteractionEnabled = NO;
        
        //设置选中的图片
        [btn setBackgroundImage:[UIImage imageNamed:@"gesture_node_highlighted"] forState:UIControlStateSelected];
     
        btn.tag = i;
    
        //九宫格计算
        int row = i/columnCount;//第几行
        int column = i%columnCount;//第几列
        int distanceY = 74;
        CGFloat margin = (kScreenWidth - columnCount * btnW) / (columnCount + 1);
        CGFloat btnX = margin + column * (margin + btnW);
        CGFloat btnY = row * (margin + btnH) + distanceY;
        btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
        height = btnH + btnY;
        [self addSubview:btn];
    }
    self.frame = CGRectMake(0, viewY, kScreenWidth, height);
   
 
}
#pragma mark - 私有方法
- (CGPoint) pointWithTouch:(NSSet *) touches {
    //1.拿到触摸的点
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    return point;

}
- (UIButton *) buttonWithPoint:(CGPoint) point {
    for (UIButton *btn in self.subviews) {
        if (CGRectContainsPoint(btn.frame, point)) {
            return btn;
        }
    }
    return nil;
}

#pragma mark - 触摸方法
- (void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    //1.拿到触摸的点
    CGPoint point = [self pointWithTouch:touches];
    //2.根据触摸的点拿到相应的按钮
    UIButton *btn = [self buttonWithPoint:point];
    //3.设置按钮的状态
    if (btn && btn.selected == NO) {
        btn.selected = YES;
        [self.selecteBtns addObject:btn];//往数组或字典添加对象时一定要先判断该对象是否为空
    }
}
- (void) touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

    //1.拿到触摸的点
    CGPoint point = [self pointWithTouch:touches];
    //2.根据触摸的点拿到相应的按钮
    UIButton *btn = [self buttonWithPoint:point];
    //3.设置按钮的状态
    if (btn && btn.selected == NO) {
        btn.selected = YES;
        [self.selecteBtns addObject:btn];
    }
    else {
        self.currentPoint = point;
    }
    [self setNeedsDisplay];
}
- (void) touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//    static int index = 0;
    if ([self.delegate respondsToSelector:@selector(lockView:didFinishPath:)]) {
            NSMutableString *path = [NSMutableString string];
            for (UIButton *btn in self.selecteBtns) {
                [path appendFormat:@"%ld",(long)btn.tag];
                NSLog(@"path = %@",path);
        }
        
        [self gestureLogicWithPassword:path];
    }
    //清空按钮的选中状态
    //makeObjectsPerformSelector 向数组中的每个对象发送方法setSelector:方法参数为 NO;
    //[self.selecteBtns makeObjectsPerformSelector:@selector(setSelected:) withObject:@(NO)];
    
    [self.selecteBtns enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *btn = obj;
        btn.selected = NO;
    }];
    
    [self.selecteBtns removeAllObjects];
    [self setNeedsDisplay];
    
}
- (void) touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self touchesEnded:touches withEvent:event];
}


#pragma mark - 绘图
- (void) drawRect:(CGRect)rect {
    
    if (self.selecteBtns.count == 0) {
        return;
    }
    UIBezierPath *path = [UIBezierPath bezierPath];
    path.lineWidth = 8;
    path.lineJoinStyle = kCGLineJoinRound;
    [[UIColor colorWithRed:32/255.0 green:210/255.0 blue:254/255.0 alpha:0.5] set];
    //遍历按钮
    for (int i = 0 ; i < self.selecteBtns.count;i++) {
        UIButton *button = self.selecteBtns[i];
        if (i == 0) {
            [path moveToPoint:button.center];//设置起点
        }
        else {
            [path addLineToPoint:button.center];//连线
        }
    }
    [path addLineToPoint:self.currentPoint];
    [path stroke];
}


- (void)didMoveToSuperview {
    
    self.changebtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.changebtn.frame = CGRectZero;
    [self.changebtn setTitle:@"修改密码" forState: UIControlStateNormal];
    [self.changebtn addTarget:self action:@selector(changePassword) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.changebtn];
    
    self.forgotbtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.forgotbtn.frame = CGRectZero;
    [self.forgotbtn addTarget:self action:@selector(forgetPassword) forControlEvents:UIControlEventTouchUpInside];
    [self.forgotbtn setTitle:@"忘记密码" forState: UIControlStateNormal];
    [self addSubview:self.forgotbtn];
    
    [self updateConstraints];
}

- (void) updateConstraints {
    [super updateConstraints];
    
    [self.changebtn autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:25];
    [self.changebtn autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:20];
    [self.changebtn autoSetDimensionsToSize:CGSizeMake(kScreenWidth/5, 44)];
    
    [self.forgotbtn autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:25];
    [self.forgotbtn autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:20];
    [self.forgotbtn autoSetDimensionsToSize:CGSizeMake(kScreenWidth/5, 44)];
}



#pragma mark -- 修改密码
- (void) changePassword {
    NSLog(@"修改密码");
    [self setTipTitle:@"请输入原密码"];
    self.mode = MODE_STATE_CHANGE;

}

#pragma mark -- 忘记密码
- (void) forgetPassword {
    NSLog(@"忘记密码");

}

#pragma mark -- 逻辑判断
- (void)gestureLogicWithPassword:(NSString *) password {
  
    switch (self.mode) {
 
        case MODE_STATE_DEFAULT: {
            [self setTipTitle:@"请再次输入密码"];
            if ([self.diskPassword isExistPassword:password]) {
                if ([self.delegate respondsToSelector:@selector(lockView:didFinishPath:)]) {
                    [self.delegate lockView:self didFinishPath:password];
                }
                
            }else {
                if (![self.diskPassword diskContainsPassword]) {
                    [self.diskPassword setPassword:password withKey:KEY_CURRENT_UID];
                }
                else {
                    [self setTipTitle:@"密码错误,请重试"];
                }
            }
        } break;

        case MODE_STATE_FORGOT: {
            
        } break;
  
        case MODE_STATE_CHANGE: {
            [self setTipTitle:@"请输入原密码"];
            if ([self.diskPassword isExistPassword:password]) {
                [self setTipTitle:@"请输入新密码"];
                [self.diskPassword removeUserPassword:KEY_CURRENT_UID];
                self.mode = MODE_STATE_DEFAULT;
            }
            else {
                [self setTipTitle:@"密码错误,请重试"];
            }
        } break;

        case MODE_STATE_CANCLE: {

        } break;
   
        default:
            break;
            
    }
}

- (void) setTipTitle:(NSString *) title {
    self.contentLabel.text = title;
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
